'use strict';
/**
 * @name 消息页的controller
 * @author zyf
 */
angular.module('metalabPartnerApp')
    .controller('MessageCtrl', ['$rootScope', '$scope', '$stateParams', '$state', '$filter', 'MetaResources', 'MetaRemind', 'MetaUtils', 'MetaSEO',
        function ($rootScope, $scope, $stateParams, $state, $filter, MetaResources, MetaRemind, MetaUtils, MetaSEO) {


            /**
             * 初始化
             * item per page
             * messageData
             */

            var per = 10;

            $scope.messageData = {};

            /**
             *
             * 从后台获取数据 并赋值
             */

            $scope.messagePromise = MetaResources.message.query({
                    userId: '_self',
                    'tag': $state.current.data.tag,
                    '_range': MetaUtils.range($state.params.page, per),
                    '_sort': '-createdAt'
                },
                function (data, headers) {
                    $scope.messageData.data = data;
                    $scope.messageData.total = headers()['x-count'];
                    $scope.messageData.currentPage = $state.params.page;
                }
            ).$promise;

            /**
             * 一旦分页点击被触发
             * 执行从后台获取数据的操作
             * 并更新页面的url参数
             */

            $scope.change = function () {
                $scope.messagePromise = MetaResources.message.query({
                        userId: '_self',
                        'tag': $state.current.data.tag,
                        '_range': MetaUtils.range($scope.messageData.currentPage, per),
                        '_sort': '-createdAt'
                    },
                    function (data) {
                        $scope.messageData.data = data;
                    }
                ).$promise;
                $state.go('.', {page: $scope.messageData.currentPage}, {notify: false, reload: false});
            };

            $scope.readMessage = function (id, index) {
                if ($scope.messageData.data[index].read) {
                    return;
                } else {
                    MetaResources.message.read({id: id}, {}, function () {
                        $scope.messageData.data[index].read = true;
                        $rootScope.unreadMessage--;
                    }, function (error) {
                        MetaRemind.error(error);
                    })
                }
            };

            MetaSEO.setSEO('我的消息');

        }]);
